package com.lznb.cloud.controller;

import com.lznb.cloud.entity.News;
import com.lznb.cloud.entity.NewsCategory;
import com.lznb.cloud.entity.Users;
import com.lznb.cloud.service.NewsCategoryService;
import com.lznb.cloud.service.NewsService;
import com.lznb.cloud.utils.JsonResultExt;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新闻表
 *
 * @author mzy
 * @email 1992lcg@163.com
 * @date ${datetime}
 */

@Controller
@RequestMapping("/newsController")
public class NewsController {
    @Autowired
    Configuration configuration;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private NewsService newsService;

    @Autowired
    private NewsCategoryService newsCategoryService;

    @Value("${web.advuploadpath}")
    private String path;

    /**
     * 根据主键查询
     *
     * @param newsId
     * @return
     */
    @GetMapping("/get")
    @ResponseBody
    News get(String newsId) {
        logger.info("根据主键查询");
        return newsService.getNews(newsId);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ResponseBody
    JsonResultExt save(News news, HttpServletRequest request) {
        logger.info("新闻表保存");
        news.setNewsPublishtime(new Date());
        news.setUpdateTime(new Date());
        news.setNewsCommentcount(0);
        news.setNewsReadingnumber(0);
        Users users = (Users) request.getSession().getAttribute("users");
        news.setUserId(users.getId());
        return newsService.save(news);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ResponseBody
    JsonResultExt update(News news) {
        logger.info("新闻表修改");
        news.setUpdateTime(new Date());
        news.setUserId("admin");
        return newsService.update(news);
    }

    /**
     * 删除
     */
    @GetMapping("/delete")
    @ResponseBody
    JsonResultExt delete(String newsId) {
        logger.info("新闻表删除");
        return newsService.delete(newsId);
    }


    /**
     * 分页查询
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/findByPage")
    @ResponseBody
    Map findByPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                   @RequestParam(value = "limit", defaultValue = "15") Integer limit, News news) {
        logger.info("新闻表分页查询");
        Map<String, String> condition = new HashMap<String, String>();
        condition.put("newsTitle", "like");
        return newsService.findByPage(page - 1, limit, news, condition);
    }

    @GetMapping("/toList")
    @ResponseBody
    public String toList(Model model) {
        List<NewsCategory> categories = newsCategoryService.findAll();
        model.addAttribute("categories", categories);
        return toPage(model, "/pages/news/list.ftl");
    }

    @GetMapping("/toAdd")
    @ResponseBody
    public String toAdd(Model model) {
        List<NewsCategory> categories = newsCategoryService.findAll();
        model.addAttribute("categories", categories);
        return toPage(model, "/pages/news/add.ftl");
    }

    @GetMapping("/toUpdate")
    @ResponseBody
    public String toUpdate(String newsId, Model model) {
        News news = newsService.getNews(newsId);
        model.addAttribute("news", news);
        List<NewsCategory> categories = newsCategoryService.findAll();
        model.addAttribute("categories", categories);
        return toPage(model, "/pages/news/edit.ftl");
    }


    /**
     * 页面跳转
     *
     * @param model
     * @param pageUrl
     * @return
     */
    public String toPage(Model model, String pageUrl) {
        Template template = null;
        try {
            template = configuration.getTemplate(pageUrl);
            StringWriter stringWriter = new StringWriter();
            template.process(model, stringWriter);
            return stringWriter.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return "";
    }

    @GetMapping("/toQueryById")
    @ResponseBody
    public String toQueryById(String newsId, Model model) {
        News news = newsService.getNews(newsId);
        model.addAttribute("news", news);
        List<NewsCategory> categories = newsCategoryService.findAll();
        model.addAttribute("categories", categories);
        return toPage(model, "/pages/news/queryById.ftl");
    }
}
